package requests.weather;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.URL;

import requests.IRequest;
import requests.settings.Settings;
import main.DemiGui;

public class WebsiteReader extends Thread implements IRequest {
	private static InformationCutter cutter = new InformationCutter();	
	private String url;
	private int refreshTime;
	private DemiGui instance;
	
	public  WebsiteReader(String url, DemiGui instance, Settings settings) {
		this.url = url;
		this.instance = instance;
		refreshTime = Integer.parseInt(settings.getSettings("weatherRefreshTime"));
	}
	
	public void run() {
		while (true) {
			try {
				String result = getWeather();
				instance.Temperature(result);
				Thread.sleep(refreshTime*1000);
			} 
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public String getWeather() {
		String result = "";
		try {	
			BufferedReader list = new BufferedReader(new FileReader(url));
			String urlString;
			urlString = list.readLine(); 
			result = getInfo(new URL(urlString));                                 
			list.close();
		}
		catch (Exception e)  {
			System.out.println("Error");
		}
		return result;
	}
	
	
	static String getInfo(URL url) throws Exception {	
		
		BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));	 
		String s, all = "";
		while ((s = in.readLine()) != null) {
			all += s;
		}
		in.close();      
		s = cutter.cut(all);
		return s;
	}

	@Override
	public void returnDEMI(String text) {
		instance.Monitor(text);
		
	}
}
